package com.iakuil.app.common.restful.filter;

import com.iakuil.app.common.core.constant.SysConstant;
import com.iakuil.app.common.core.util.RequestIdUtils;
import com.iakuil.app.common.core.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * RequestId Filter
 *
 * @author Kai
 */
@Slf4j
public class RequestIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (!request.getMethod().equalsIgnoreCase("OPTIONS")) {
            String rid = ServletUtils.getHeaderIgnoreCase(request, SysConstant.HEADER_X_REQUEST_ID);
            if (rid == null) {
                RequestIdUtils.generateRequestId();
                rid = RequestIdUtils.getRequestId().toString();
            }
            log.debug("request uri: {}, request id: {}", request.getRequestURI(), rid);

            try {
                MDC.put(SysConstant.MDC_KEY_RID, rid);
                chain.doFilter(request, response);
            } finally {
                RequestIdUtils.removeRequestId();
                MDC.clear();
            }
        }
    }
}
